package com.llho.core.dao.impl;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateSystemException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.llho.core.dao.ProductDAO;
import com.llho.core.domain.Catalog;
import com.llho.core.domain.Product;

public class ProductDAOImpl extends HibernateDaoSupport implements ProductDAO {

	@Override
	public Product getById(Long id) {
		Product kq = null;
		try {
			kq = (Product) getHibernateTemplate().get(Product.class, id);
		} catch (HibernateSystemException e) {
			e.printStackTrace();
		}
		return kq;
	}
	
	@Override
	public List<Product> getByCatalog(Catalog entity) {
		List<Product> kq = null;
		try {
			String hql = "from Product p where p.catalog =:cat";
			kq = getHibernateTemplate().findByNamedParam(hql, "cat", entity);
		} catch (HibernateSystemException e) {
			e.printStackTrace();
		}
		return kq;
	}

	@Override
	public List<Product> getAll() {
		List<Product> kq = null;
		try {
			//String hql = "from Product";
			//kq = getHibernateTemplate().find(hql);
			kq = getHibernateTemplate().loadAll(Product.class);
			
			for (Product product : kq) {
				Hibernate.initialize(product);
				Hibernate.initialize(product.getCatalog());
				Hibernate.initialize(product.getImages());
			}
			
		} catch (HibernateSystemException e) {
			e.printStackTrace();
		}
		return kq;
	}

	@Override
	public void delete(Product entity) {
		try {
			Product product = (Product) getHibernateTemplate().load(Product.class,
					entity.getId());
			getHibernateTemplate().delete(product);
		} catch (HibernateSystemException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void addNew(Product entity) {
		try {
			getHibernateTemplate().saveOrUpdate(entity);
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void update(Product entity) {
		try {
			getHibernateTemplate().update(entity);
		} catch (HibernateSystemException e) {
			e.printStackTrace();
		}
	}
}
